/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Enhance as FormItem} from '../form-item';
import * as Sensor from '../../../widgets/visibility-sensor.jsx';
import * as cx from 'classnames';

@FormItem({
  type: 'editor-code',
  test: (path, config) => /(?:^|\/)form-item$/.test(path)
    && ~['shell-editor'].indexOf(config.type),
  validateSchema: 'http://amis.baidu.com/schemas/form.json#/definitions/formItem'
})
export default class JsonEditor extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object,
    inputClassName: PropTypes.string
  };

  static defaultProps = {
    value: '',
    width: '100%',
    height: 250
  };

  constructor(props) {
    super(props);

    this.state = {
      Editor: null
    };
    this.changeValue = this.changeValue.bind(this);
    this.handleVisibleChange = this.handleVisibleChange.bind(this);
  }

  changeValue(value) {
    this.props.setValue(value);
  }

  handleVisibleChange(isVisible) {
    if (this.state.Editor || !isVisible) {
      return;
    }

    require(['../../../widgets/editor/code-mirror'], component => this.setState({Editor: component.default}));
  }

  render() {
    const {
      disabled,
      inputClassName,
      placeholder,
      type,
      name,
      width,
      height
    } = this.props;

    const map = {
      'shell-editor': 'shell'
    };

    const commonProps = {
      className: cx('form-control', inputClassName),
      disabled,
      key:"input",
      placeholder,
      name: name,
      onChange: this.changeValue,
      value: this.props.getValue() || '',
      width,
      height,
      mode: map[type] || 'json'
    };
    const Editor = this.state.Editor;

    return Editor ? (
      <Editor
        {...commonProps}
      />
    ) : (
      <Sensor onChange={this.handleVisibleChange}>
        <div className="text-center m-t-lg">
          <i className="fa fa-spinner fa-spin fa-3x fa-fw" />
        </div>
      </Sensor>
    );
  }
}
